package de.bib.blue.manage.finance.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import de.bib.blue.manage.finance.database.ResourceDatabase;

public class LoadFile {

	private static final String PATH_PARSER = "D:/Private/Campus/Skripsi/Monitoring/skripsi/Temp/Data";
	private List<Object[]> record;

	private ResourceDatabase rd;

	public LoadFile(ResourceDatabase rd) {
		this.rd = rd;
	}

	public void loadsFile() throws IOException, SQLException {
		File file = new File(PATH_PARSER);
		for (File f : file.listFiles()) {

			record = new LinkedList<Object[]>();

			if (checkFile(f.getName())) {
				if (f.isFile()) {
					parsingFile(f);

					renamingFile(f.getParent(), f.getName(), "F");

					insertFile(record);
				}
			}
		}
	}

	private String renamingFile(String path, String oldName, String action) {
		// File (or directory) with old name
		File file = new File(path + "/" + oldName);

		// File (or directory) with new name
		File file2 = new File(path + "/" + action + oldName);

		// Rename file (or directory)
		boolean success = file.renameTo(file2);
		if (!success) {
			System.out.println("File was not successfully renamed");
		}
		return file2.getName();
	}

	public void parsingFile(File f) throws IOException {
		FileInputStream inputWorkbook = new FileInputStream(f);

		Workbook w;
		try {
			w = Workbook.getWorkbook(inputWorkbook);
			Sheet sheet = w.getSheet(0);

			for (int i = 4; i < sheet.getRows(); i++) {
				if (i % 2 == 0) {
					String[] objects = new String[6];
					for (int j = 1; j < 7; j++) {
						Cell cell = sheet.getCell(j, i);
						objects[j - 1] = cell.getContents();
					}
					record.add(objects);
				}
			}

			inputWorkbook.close();

		} catch (BiffException e) {
			e.printStackTrace();
		}

	}

	private void insertFile(List<Object[]> record) throws SQLException {
		rd.insertTable(record);
	}

	private boolean checkFile(String name) {
		return (name.startsWith("J"));
	}

	public static void main(String[] args) throws Exception {
		LoadFile lF = new LoadFile(ResourceDatabase.getInstance());
		lF.loadsFile();
	}
}
